const { verifyToken, getTokenFromHeader } = require('../utils/jwt');
const jwt = require('jsonwebtoken');
require('dotenv').config();

// 身份验证中间件
const authMiddleware = (req, res, next) => {
  try {
    // 获取token
    const token = getTokenFromHeader(req);
    
    console.log('Token from header:', token ? 'Present' : 'Absent');
    
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供认证令牌'
      });
    }
    
    // 验证token
    const decoded = verifyToken(token);
    
    if (!decoded) {
      console.error('Token verification failed for token:', token ? (token.length > 20 ? token.substring(0, 20) + '...' : token) : 'undefined/null');
      return res.status(401).json({
        success: false,
        message: '无效的认证令牌'
      });
    }
    
    console.log('Token verified successfully for user:', decoded.username);
    
    // 将用户信息保存到请求对象
    req.user = {
      userId: decoded.userId,
      username: decoded.username
    };
    
    next();
  } catch (error) {
    console.error('Auth middleware error:', error.message);
    return res.status(401).json({
      success: false,
      message: '身份验证失败: ' + error.message
    });
  }
};

module.exports = authMiddleware;